<template>
  <div class="task-list-view" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
    <AppHeader title="任务列表">
      <template #left>
        <!-- No back button on the main task list page -->
        <el-button circle @click="goToWeather">
          <el-icon><mostly-cloudy /></el-icon>
        </el-button>
      </template>
      <template #right>
        <el-button 
          type="primary" 
          circle
          size="medium"
          @click="goToAnniversaries"
        >
          <el-icon><Calendar /></el-icon>
          <span>纪念日</span>
        </el-button>
      </template>
    </AppHeader>

    <el-pull-refresh @refresh="onRefresh">
      <div class="task-section">
        <h2>待办任务</h2>
        <div 
          v-for="task in pendingTasks" 
          :key="task.id" 
          class="task-card"
          @click="goToEditTask(task.id)"
        >
          <el-checkbox
            :model-value="task.status === 2"
            @change="val => handleTaskComplete(task, val)"
            @click.stop="handleTaskComplete(task, val)"
          />
          <div class="task-content">
            <div class="task-title">{{ task.title }}</div>
            <div class="task-time" v-if="task.expectTime">{{ task.expectTime }}</div>
          </div>
        </div>
        <div v-if="pendingTasks.length === 0" class="no-task">暂无待办任务</div>
      </div>
      <div class="task-section completed">
        <h2>已完成</h2>
        <div 
          v-for="task in completedTasks" 
          :key="task.id" 
          class="task-card completed"
          @click="goToEditTask(task.id)"
        >
          <el-checkbox
            :model-value="task.status === 2"
            @change="val => handleTaskComplete(task, val)"
            @click.stop="handleTaskComplete(task, val)"
          />
          <div class="task-content">
            <div class="task-title">{{ task.title }}</div>
            <div class="task-time" v-if="task.expectTime">{{ task.expectTime }}</div>
          </div>
        </div>
        <div v-if="completedTasks.length === 0" class="no-task">暂无已完成任务</div>
      </div>

      <!-- 添加浮动按钮 -->
      <div class="floating-add-button">
        <el-button 
          type="primary" 
          circle
          size="large"
          @click="showAddTaskDialog"
        >
          <el-icon><Plus /></el-icon>
        </el-button>
      </div>

      <!-- 添加新任务对话框 -->
      <el-dialog
        v-model="addTaskVisible"
        title="添加任务"
        width="50%"
      >
        <el-form :model="newTask" label-width="100px">
          <el-form-item label="任务标题" required>
            <el-input v-model="newTask.title"></el-input>
          </el-form-item>
          <el-form-item label="任务描述">
            <el-input type="textarea" v-model="newTask.description"></el-input>
          </el-form-item>
          <el-form-item label="优先级" required>
            <el-select v-model="newTask.level">
              <el-option label="重要且紧急" :value="1"></el-option>
              <el-option label="重要不紧急" :value="2"></el-option>
              <el-option label="不重要但紧急" :value="3"></el-option>
              <el-option label="不重要不紧急" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预期完成时间">
            <el-date-picker 
              v-model="newTask.expectTime" 
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addTaskVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddTask">确定</el-button>
        </template>
      </el-dialog>

      <!-- 任务详情对话框 -->
      <el-dialog
        v-model="taskDetailVisible"
        title="任务详情"
        width="50%"
      >
        <template v-if="currentTask">
          <div class="task-detail">
            <h3>{{ currentTask.title }}</h3>
            <p>{{ currentTask.description }}</p>
            <div class="task-meta">
              <p>优先级: {{ getPriorityLabel(currentTask.level) }}</p>
              <p>预期完成时间: {{ currentTask.expectTime }}</p>
            </div>
          </div>
        </template>
      </el-dialog>

      <!-- 添加子任务对话框 -->
      <el-dialog
        v-model="addSubtaskVisible"
        title="添加子任务"
        width="50%"
      >
        <el-form :model="newSubtask" label-width="100px">
          <el-form-item label="任务标题">
            <el-input v-model="newSubtask.title"></el-input>
          </el-form-item>
          <el-form-item label="任务描述">
            <el-input type="textarea" v-model="newSubtask.description"></el-input>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="newSubtask.level">
              <el-option label="重要且紧急" :value="1"></el-option>
              <el-option label="重要不紧急" :value="2"></el-option>
              <el-option label="不重要但紧急" :value="3"></el-option>
              <el-option label="不重要不紧急" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预期完成时间">
            <el-date-picker 
              v-model="newSubtask.expectTime" 
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addSubtaskVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubtask">确定</el-button>
        </template>
      </el-dialog>
    </el-pull-refresh>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { Plus, Calendar, MostlyCloudy } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import AppHeader from '../components/AppHeader.vue'

export default {
  name: 'TaskListView',
  components: {
    Plus,
    Calendar,
    AppHeader,
    MostlyCloudy,
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const taskDetailVisible = ref(false)
    const addSubtaskVisible = ref(false)
    const addTaskVisible = ref(false)
    const currentTask = ref(null)
    const currentParentTask = ref(null)
    const editingTask = ref(null)
    const newSubtask = ref({
      title: '',
      description: '',
      level: 1,
      expectTime: null
    })
    const newTask = ref({
      title: '',
      description: '',
      level: 1,
      expectTime: null
    })

    let startX = 0;
    const minSwipeDistance = 50; // Minimum distance in pixels for a swipe

    const handleTouchStart = (event) => {
      startX = event.touches[0].clientX;
    };

    const handleTouchMove = () => {
      // Optional: prevent default to avoid scrolling while swiping horizontally
    };

    const handleTouchEnd = (event) => {
      const endX = event.changedTouches[0].clientX;
      const diffX = endX - startX;

      if (diffX > minSwipeDistance) {
        // Swipe right detected
        goToWeather();
      }
    };

    const goToWeather = () => {
      console.log('Navigating to weather page');
      router.push({ name: 'Weather' });
    };

    // 使用计算属性获取 store 中的任务
    const tasks = computed(() => {
      console.log('tasks computed 被调用，当前 store.tasks:', store.state.tasks)
      return store.state.tasks
    })

    // 使用计算属性过滤待办任务
    const pendingTasks = computed(() => {
      console.log('pendingTasks computed 被调用，当前 tasks:', tasks.value)
      return tasks.value.filter(task => task.status == 1)
    })

    // 使用计算属性过滤已完成任务
    const completedTasks = computed(() => {
      console.log('completedTasks computed 被调用，当前 tasks:', tasks.value)
      return tasks.value.filter(task => task.status == 2)
    })

    // 在组件挂载时获取数据
    onMounted(async () => {
      console.log('TaskListView mounted')
      await store.dispatch('fetchTasks')
    })

    const showTaskDetail = (task) => {
      currentTask.value = task
      taskDetailVisible.value = true
    }

    const showAddSubtaskDialog = (task) => {
      currentParentTask.value = task
      addSubtaskVisible.value = true
    }

    const showAddTaskDialog = () => {
      newTask.value = {
        title: '',
        description: '',
        level: 1,
        expectTime: null
      }
      addTaskVisible.value = true
    }

    const handleTaskComplete = async (task, checked) => {
      const newStatus = checked ? 2 : 1
      if (task.status !== newStatus) {
        await store.dispatch('updateTask', { ...task, status: newStatus })
        await store.dispatch('fetchTasks')
        if (editingTask.value && editingTask.value.id === task.id) {
          editingTask.value = null
        }
      }
    }

    const handleAddSubtask = async () => {
      try {
        const response = await axios.post('http://localhost:8080/zwart/user/task/insert', {
          ...newSubtask.value,
          parentId: currentParentTask.value.id,
          status: 1,
          expectTime: newSubtask.value.expectTime || null
        })
        if (response.data.code === 0) {
          await store.dispatch('fetchTasks')
          addSubtaskVisible.value = false
          newSubtask.value = {
            title: '',
            description: '',
            level: 1,
            expectTime: null
          }
        }
      } catch (error) {
        console.error('Error adding subtask:', error)
      }
    }

    const handleAddTask = async () => {
      try {
        const response = await axios.post('http://localhost:8080/zwart/user/task/insert', {
          ...newTask.value,
          parentId: 0,
          status: 1,
          expectTime: newTask.value.expectTime || null
        })
        if (response.data.code === 0) {
          await store.dispatch('fetchTasks')
          addTaskVisible.value = false
          newTask.value = {
            title: '',
            description: '',
            level: 1,
            expectTime: null
          }
        }
      } catch (error) {
        console.error('Error adding task:', error)
      }
    }

    const handleUpdateTask = async () => {
      if (!editingTask.value || editingTask.value.id === null) {
        console.error('Task data is not ready for update or missing ID');
        return;
      }

      const taskToUpdate = {
        id: editingTask.value.id,
        title: editingTask.value.title,
        description: editingTask.value.description,
        expectTime: editingTask.value.expectTime,
        level: editingTask.value.level,
        status: editingTask.value.status
      };

      console.log('Updating task with data:', taskToUpdate);

      try {
        const response = await axios.post('http://localhost:8080/zwart/user/task/update', taskToUpdate);

        if (response.data === true) {
          console.log('Task updated successfully');
          editingTask.value = null;
          await store.dispatch('fetchTasks');
        } else {
          console.error('Failed to update task: Backend returned false');
        }
      } catch (error) {
        console.error('Error updating task:', error);
      }
    }

    const getPriorityLabel = (level) => {
      const labels = {
        1: '重要且紧急',
        2: '重要不紧急',
        3: '不重要但紧急',
        4: '不重要不紧急'
      }
      return labels[level]
    }

    const onRefresh = async (done) => {
      await store.dispatch('fetchTasks')
      done()
    }

    const goToAnniversaries = () => {
      console.log('Navigating to anniversaries')
      router.push({ name: 'Anniversary' })
    }

    const goToEditTask = (taskId) => {
      router.push({ name: 'TaskEdit', params: { id: taskId } });
    };

    return {
      tasks,
      pendingTasks,
      completedTasks,
      taskDetailVisible,
      addSubtaskVisible,
      addTaskVisible,
      currentTask,
      currentParentTask,
      editingTask,
      newSubtask,
      newTask,
      showTaskDetail,
      showAddSubtaskDialog,
      showAddTaskDialog,
      handleTaskComplete,
      handleAddSubtask,
      handleAddTask,
      handleUpdateTask,
      getPriorityLabel,
      onRefresh,
      goToAnniversaries,
      goToEditTask,
      handleTouchStart,
      handleTouchMove,
      handleTouchEnd,
      goToWeather
    }
  }
}
</script>

<style lang="scss" scoped>
.task-list-view {
  padding: 60px 15px 65px; // Add padding to account for the fixed header

  .task-section {
    margin-bottom: 20px;

    h2 {
      margin-bottom: 12px;
      color: #303133;
      font-size: 16px;
      padding-left: 5px;
    }

    &.completed {
      .task-item {
        color: #909399;
      }
    }
  }

  .task-items {
    .task-item {
      margin-bottom: 10px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

      .task-main {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        cursor: pointer;

        :deep(.el-checkbox) {
          flex: 1;
          margin-right: 10px;
        }

        &:active {
          background-color: #f5f7fa;
        }
      }

      .add-subtask-btn {
        padding: 4px;
      }
    }
  }

  .subtask-list {
    margin-left: 20px;
    padding: 0 12px 12px;
    background: #f8f9fa;

    .subtask-item {
      margin-bottom: 8px;
      padding: 8px 0;
    }
  }

  .floating-add-button {
    position: fixed;
    right: 20px;
    bottom: 70px; // 调整位置以避免被底部导航遮挡
    z-index: 1000;

    .el-button {
      width: 44px;
      height: 44px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }
  }

  :deep(.el-dialog) {
    width: 90% !important;
    max-width: none;
    margin: 0 auto;
    border-radius: 12px;
    overflow: hidden;

    .el-dialog__header {
      margin: 0;
      padding: 15px;
      border-bottom: 1px solid #dcdfe6;
    }

    .el-dialog__body {
      padding: 15px;
    }

    .el-dialog__footer {
      padding: 10px 15px;
      border-top: 1px solid #dcdfe6;
    }

    .el-form-item {
      margin-bottom: 15px;
    }
  }

  .task-card {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px #eee;
    padding: 12px 16px;
    margin-bottom: 12px;
    cursor: pointer
  }
  .task-card .el-checkbox {
    margin-right: 12px;
  }
  .task-card.completed .task-title {
    color: #bbb;
    text-decoration: line-through;
  }
  .task-title {
    font-size: 16px;
    font-weight: 500;
  }
  .task-time {
    font-size: 12px;
    color: #999;
  }
  .no-task {
    color: #bbb;
    padding: 16px 0;
    text-align: center;
  }
}

.task-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: var(--el-color-primary);
  color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.task-list-header h2 {
  margin: 0;
  color: #fff;
  font-size: 18px;
}

// Add style for the button to handle icon and text layout
.app-header .el-button.is-circle {
  padding: auto; /* Revert padding for non-circle layout */
  width: auto; /* Revert width */
  height: auto; /* Revert height */
  border-radius: 20px; /* Make it pill-shaped or adjust as needed */
}

.app-header .el-button span {
  display: flex;
  align-items: center;
}

.app-header .el-button .el-icon {
  margin-right: 4px; /* Space between icon and text */
}
</style> 